<?php
/* This file is part of Mirasol CMS
   (C) 2011 by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/core.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/db.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/login.php";

if (empty ($login['username']))
  exit;
	
$connection = db_open ();

/* Save data */
if (isset ($_POST['id']) && !empty ($_POST['id']))
{
	$id = mysql_real_escape_string ($_POST['id']);
	
	/* Save new file if any */
	if (isset ($_FILES['upfile']) && !empty ($_FILES['upfile']['name']))
	  {
			/* Delete old file */
			if ($_POST['id'] != "new")
				{
					$result = mysql_query ("SELECT filename FROM ".db_maketablename ($table_files)." WHERE id='$id' LIMIT 1");
					if (mysql_num_rows ($result) > 0)
						{
							$row = mysql_fetch_array ($result);
							$oldfile = "{$_SERVER['DOCUMENT_ROOT']}$app_filespath/{$row['filename']}";
							if (file_exists ($oldfile))
								unlink ($oldfile);
						}
					mysql_free_result ($result);
				}
			
			/* Move new file into place */
			$ext = pathinfo ($_FILES['upfile']['name'], PATHINFO_EXTENSION);
			$savefile = "{$_SERVER['DOCUMENT_ROOT']}$app_filespath/".time ().".$ext";
			move_uploaded_file ($_FILES['upfile']['tmp_name'], $savefile);
			
			/* Save meta data */
			$filename = basename ($savefile);
			$origname = mysql_real_escape_string ($_FILES['upfile']['name']);
			$name = !empty ($_POST['name']) ? mysql_real_escape_string ($_POST['name']) : $origname;
			$comment = mysql_real_escape_string (trim ($_POST['comment']));
			
      $mime = get_mime_type ($savefile);
			$doctype = !empty ($mimetypes[$mime]) ? $mimetypes[$mime] : 0;
			
			if ($_POST['id'] == "new" && $doctype != 0)
			  mysql_query ("INSERT INTO ".db_maketablename ($table_files)." (filename, filename_orig, name, comment, doctype) VALUES ('$filename', '$origname', '$name', '$comment', '$doctype')");
			else if ($doctype != 0)
			  mysql_query ("UPDATE ".db_maketablename ($table_files)." SET filename='$filename', filename_orig='$origname', name='$name', comment='$comment', doctype='$doctype' WHERE id='$id'");
		}
	else
	  {
			$origname = "N/A";
			$result = mysql_query ("SELECT filename_orig FROM ".db_maketablename ($table_files)." WHERE id='$id' LIMIT 1");
			if (mysql_num_rows ($result) > 0)
				{
					$row = mysql_fetch_array ($result);
					$origname = mysql_real_escape_string ($row['filename_orig']);
				}
			mysql_free_result ($result);
			$name = !empty ($_POST['name']) ? mysql_real_escape_string ($_POST['name']) : $origname;
			$comment = mysql_real_escape_string (trim ($_POST['comment']));
			if ($_POST['id'] == "new")
			  mysql_query ("INSERT INTO ".db_maketablename ($table_files)." (name, comment) VALUES ('$name', '$comment')");
			else
			  mysql_query ("UPDATE ".db_maketablename ($table_files)." SET name='$name', comment='$comment' WHERE id='$id'");
		}
}

/* Load data if this is an edit */
if (isset ($_GET['fid']) && !empty ($_GET['fid']))
{
	$result = mysql_query ("SELECT id, filename, filename_orig, name, comment, doctype FROM ".db_maketablename ($table_files)." WHERE id='".mysql_real_escape_string ($_GET['fid'])."'");
	if (mysql_num_rows ($result) > 0)
	  {
			$row = mysql_fetch_array ($result);
			$id = $row['id'];
			$file = "$app_filespath/{$row['filename']}";
			$filename = htmlentities ($row['filename_orig'], ENT_COMPAT, "UTF-8", false);
			$name = htmlentities (stripslashes ($row['name']), ENT_COMPAT, "UTF-8", false);
			$comment = htmlentities (stripslashes ($row['comment']), ENT_COMPAT, "UTF-8", false);
			
			/* Calculate a reasonable image size */
			if ($row['doctype'] == 1) /* Image */
			  {
					list ($width, $height) = getimagesize ("{$_SERVER['DOCUMENT_ROOT']}$file");
					if ($width > 200)
            {
              $newwidth = 200;
              $difftoheight = (($width - $newwidth) * 100) / $width;
              $newheight = round ($height - ($height * $difftoheight / 100));
              
              $width = $newwidth;
              $height = $newheight;
              if ($height > 270)
                {
                  $newheight = 270;
                  $difftowidth = (($height - $newheight) * 100) / $height;
                  $newwidth = round ($width - ($width * $difftowidth / 100));
                }
            }
          else
            {
							$newheight = $height;
					    $newwidth = $width;
						}
				}
		}
	mysql_free_result ($result);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:php="http://php.net/xsl" xml:lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<?php
if (isset ($_GET['fid']) && !empty ($_GET['fid']) || isset ($_GET['new']))
{
?>
    <meta name="robots" content="noindex, nofollow" />
    <title><?=isset ($_GET['new']) ? "New file" : "Edit file" ?></title>
		
		<link type="text/css" href="./styles/overcast/jquery-ui.css" rel="Stylesheet" />
    <script type="text/javascript" src="./scripts/jquery.min.js"></script>
    <script type="text/javascript" src="./scripts/jquery-ui.min.js"></script>
		<script type="text/javascript">
		  $(document).ready (function ()
			  {
					// Buttons
					$("input:button, input:submit", ".operate" ).button ();
				});
		</script>

    <link rel="icon" href="./favicon.ico" type="image/x-icon" /> 
    <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="./styles/mirasol.css" type="text/css" media="screen" />
<?php
} /* isset ($_GET['fid']) && !empty ($_GET['fid']) || isset ($_GET['new']) */
?>
  </head>

  <body>
<?php
if (isset ($_GET['fid']) && !empty ($_GET['fid']) || isset ($_GET['new']))
{
?>
    <div id="dialog" style="height: 355px;">
			<form method="post" action="<?=$_SERVER['PHP_SELF'] ?>" enctype="multipart/form-data">
			  <table cellpadding="0" cellspacing="0">
					<tr>
						<td colspan="2"><h4><?=isset ($id) ? $filename : "New file" ?></h4></td>
					</tr>
					<tr>
						<td class="aligntop" style="width: 200px; padding-right: 5px;">
<?php
if (isset ($id))
{
?>
							<img src="<?=$file ?>" alt="<?=$name ?>" style="width: <?=$newwidth ?>px; height: <?=$newheight ?>px;" />
<?php
} /* isset ($id) */
?>
              <input type="file" name="upfile" value="Upload" class="textfield" style="width: 190px" />
						</td>
						<td class="aligntop">
							<input type="text" name="name" value="<?=isset ($id) ? $name : "" ?>" style="margin-bottom: 5px; width: 350px;" class="textfield" /><br />
							<textarea name="comment" style="width: 350px; height: 270px;"><?=isset ($id) ? $comment : "" ?></textarea>
						</td>
					</tr>
					<tr>
						<td colspan="2" class="operate"><input type="hidden" name="id" value="<?=isset ($id) ? $id : "new" ?>" /><input type="submit" value="Save" class="alignright button btnstdsize" /></td>
					</tr>
				</table>
			</form>
		</div>
<?php
} /* isset ($_GET['fid']) && !empty ($_GET['fid']) || isset ($_GET['new']) */
else
{
?>
  <body onload="window.close ();">
<?php
} /* NOT isset ($_GET['fid']) && !empty ($_GET['fid']) || isset ($_GET['new']) */
?>
  </body>
</html>
<?php
db_close ($connection);
?>
